import 'dart:typed_data';

import 'package:universal_html/html.dart' as html;

import '../web/image_picker_web.dart';

/// 选择成功的回调
typedef OnTakeCallback = Function(Uint8List bytes, String fileName);
typedef OnTakeFailCallback = Function();

/// Web文件选择
class WebFilePickerUtil {
  /// 选择图片
  static void takeImage(
      OnTakeCallback onTake, OnTakeFailCallback? onFail) async {
    html.File? pickedFile = await ImagePickerWeb.getImageAsFile();
    _handleTakeResult(pickedFile, onTake, onFail);
  }

  /// 选择视频
  static void takeVideo(
      OnTakeCallback onTake, OnTakeFailCallback? onFail) async {
    html.File? pickedFile = await ImagePickerWeb.getVideoAsFile();
    _handleTakeResult(pickedFile, onTake, onFail);
  }

  static _handleTakeResult(html.File? pickedFile, OnTakeCallback onTake,
      OnTakeFailCallback? onFail) async {
    if (pickedFile == null) {
      onFail?.call();
      return;
    }
    // 文件名
    var fileName = pickedFile.name;
    // 文件转字节数组
    final reader = html.FileReader();
    reader.readAsArrayBuffer(pickedFile);
    await reader.onLoad.first;
    var bytes = reader.result as Uint8List;
    onTake.call(bytes, fileName);
  }
}
